package fr.ginvest.implementation;

import java.util.Collection;
import java.util.Date;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import fr.ginvest.entity.Club;
import fr.ginvest.entity.Demande;
import fr.ginvest.entity.Demande.Etat;
import fr.ginvest.entity.DemandeClubAmi;
import fr.ginvest.interfaces.DemandeClubAmiFacadeRemote;

/**
 * Session Bean implementation class DemandeClubAmi
 */
@Stateless
public class DemandeClubAmiFacade implements DemandeClubAmiFacadeRemote {

	@PersistenceContext
	protected EntityManager entityMgr;
	public DemandeClubAmiFacade() {
	}	

	public DemandeClubAmiFacade(EntityManager entityMgr) {
		this.entityMgr = entityMgr;
	}

    public DemandeClubAmi findDemandeClubAmiById(int id) {
        return entityMgr.find(DemandeClubAmi.class, id);
    }
    
    public void deleteDemandeClubAmi(DemandeClubAmi dca) {
    	entityMgr.remove(dca);
    }
    
    public DemandeClubAmi updateDemandeClubAmi(DemandeClubAmi dca) {
    	return entityMgr.merge(dca);
    }
    
    public DemandeClubAmi addDemandeClubAmi(DemandeClubAmi dca) {
    	entityMgr.persist(dca);
		return dca;
    }

	@SuppressWarnings("unchecked")
	@Override
	public Collection<DemandeClubAmi> listDemandeByClub(Club club) {
		final String queryString = "select d from DemandeClubAmi d where d.destination=:club and d.etat=:etat";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("club", club);
		query.setParameter("etat", Etat.NON_TRAITE);
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<DemandeClubAmi> listEnvDemandeByClub(Club club) {
		final String queryString = "select d from DemandeClubAmi d where d.origine=:club";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("club", club);
		return query.getResultList();
	}

	@Override
	public void acceptDemande(DemandeClubAmi d) {
		d.setEtat(Demande.Etat.ACCEPTE);
		d.setDateTraite(new Date());
		entityMgr.merge(d);
		
		Club c1 = d.getOrigine();
		Club c2 = d.getDestination();
		c2.addAmi(c1);
		entityMgr.merge(c2);
		entityMgr.merge(c1);
		
	}

}
